/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.renren.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import io.renren.common.exception.ErrorCode;
import io.renren.common.exception.RenException;
import io.renren.common.service.impl.BaseServiceImpl;
import io.renren.common.utils.DateUtils;
import io.renren.common.validator.AssertUtils;
import io.renren.dao.UserDao;
import io.renren.dto.LoginDTO;
import io.renren.entity.TokenEntity;
import io.renren.entity.UserEntity;
import io.renren.modules.entity.BsConsumerEntity;
import io.renren.service.TokenService;
import io.renren.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@AllArgsConstructor
public class UserServiceImpl extends BaseServiceImpl<UserDao, UserEntity> implements UserService {
    private final TokenService tokenService;

    @Override
    public UserEntity getByMobile(String mobile) {
        return baseDao.getUserByMobile(mobile);
    }

    @Override
    public UserEntity getUserByUserId(Long userId) {
        return baseDao.getUserByUserId(userId);
    }

    @Override
    public Map<String, Object> wxLogin(String code) {
        // todo 根据微信sdk获取微信用户信息，包含openId和头像、昵称信息

        // todo 根据微信用户信息创建用户
        BsConsumerEntity bsConsumer = new BsConsumerEntity();
        bsConsumer.setConsumerNo("");
        bsConsumer.setCreateTime(new Date());
        bsConsumer.setUpdateTime(new Date());
        bsConsumer.setWxOpenId("");

        // todo 保存用户信息


        //获取登录token
        return createToken(bsConsumer.getConsumerNo());
    }


    @Override
    public Map<String, Object> aliLogin(String code) {
        // todo 根据微信sdk获取微信用户信息，包含openId和头像、昵称信息

        // todo 根据微信用户信息创建用户
        BsConsumerEntity bsConsumer = new BsConsumerEntity();
        bsConsumer.setConsumerNo("");
        bsConsumer.setCreateTime(new Date());
        bsConsumer.setUpdateTime(new Date());
        bsConsumer.setWxOpenId("");

        // todo 保存用户信息


        //获取登录token
        return createToken(bsConsumer.getConsumerNo());
    }

    public Map<String, Object> createToken(String consumerNo) {
        TokenEntity tokenEntity = tokenService.createToken(consumerNo);

        Map<String, Object> map = new HashMap<>(2);
        map.put("token", tokenEntity.getToken());
        map.put("expire", tokenEntity.getExpireDate().getTime() - System.currentTimeMillis());

        return map;
    }


}